<template>
  <div class="chart-container">
    <div ref="chart" class="chart"></div>
    <div class="detail-panel" :class="{ 'show': drawerVisible, 'expanded': isExpanded }">
      <div class="detail-header">
        <div class="header-left">
          <span v-if="!isExpanded" class="expand-btn" @click="handleExpand">展开</span>
          <span v-else class="expand-btn" @click="handleCollapse">收起</span>
        </div>
        <div class="header-right">
          <span class="close-btn" @click="handleClose">×</span>
        </div>
      </div>
      <div class="detail-body" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(255, 255, 255, 0.7)">
        <div v-if="hasNoDetailData" class="no-data-mask">
          <img src="../KnowledgeGraphItem/images/nodata.gif" class="no-data-img">
          <div class="no-data-text">此节点无详情数据</div>
        </div>
        <template v-else>
          <div class="node-info">
            <span class="attr-tag attr-tag1">属性名</span>
            <h3>{{ nodeDetail.nodeName }}</h3>
          </div>
          <div class="node-info">
            <span class="attr-tag attr-tag3">别名</span>
            <h3>{{ nodeDetail.nodeAlias }}</h3>
          </div>
          <div class="node-info">
            <span class="attr-tag attr-tag2">属性</span>
            <h3>{{ nodeDetail.nodeAttributes }}</h3>
          </div>
          <div class="detail-content" >
            <span class="attr-tag attr-tag4">描述</span>
            <p>{{ nodeDetail.nodeDescription }}</p>
          </div>
          <div class="detail-content">
            <span class="attr-tag attr-tag5">物理意义</span>
            <p>{{ nodeDetail.nodePhysicalSignificance }}</p>
          </div>
          <div class="detail-content">
            <span class="attr-tag attr-tag6">化学意义</span>
            <p>{{ nodeDetail.nodeChemicalSignificance }}</p>
          </div>
          <div class="node-info">
            <span class="attr-tag attr-tag7">数学依赖性</span>
            <h3>{{ nodeDetail.nodeMathematicalDependency }}</h3>
          </div>
          <div class="node-info">
            <span class="attr-tag attr-tag8">实验依据</span>
            <h3>{{ nodeDetail.nodeExperimentalBasis }}</h3>
          </div>
          <div class="detail-content">
            <span class="attr-tag attr-tag9">历史背景</span>
            <p>{{ nodeDetail.nodeHistoricalBackground }}</p>
          </div>
          <div class="detail-content">
            <span class="attr-tag attr-tag10">典型案例</span>
            <p>{{ nodeDetail.nodeTypicalCases }}</p>
          </div>
          <div class="detail-content">
            <span class="attr-tag attr-tag11">学科前沿</span>
            <p>{{ nodeDetail.nodeFrontier }}</p>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import knowledgeGraph from '@/api/knowledgeGraph'

export default {
  name: 'GridChart',
  props: {
    graphData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chart: null,
      processedData: null,
      drawerVisible: false,
      isExpanded: false,
      nodeDetail: {},
      loading: false
    };
  },
  watch: {
    graphData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.processedData = this.convertTreeToGraph(newVal);
          if (!this.chart) {
            this.$nextTick(() => {
              this.initChart();
            });
          } else {
            this.chart.setOption({
              series: [{
                data: this.processedData.nodes,
                links: this.processedData.links,
                categories: this.processedData.categories
              }]
            });
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initChart();
      }, 100);
    });
    document.addEventListener('click', this.handleOutsideClick);
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    document.removeEventListener('click', this.handleOutsideClick);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    convertTreeToGraph(treeData) {
      const nodes = [];
      const links = [];
      const categories = [];
      let categoryIndex = 0;
      
      // 定义一些不同的颜色
      const colors = [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4'
      ];

      const traverse = (node, parentId = null, level = 0) => {
        // 根据层级计算节点大小
        const baseSize = 60;
        const sizeDecrement = 10;
        const nodeSize = Math.max(baseSize - (level * sizeDecrement), 20);

        const nodeName = node.label || node.name || node.nodeName;
        const nodeId = node.id || nodeName;

        const currentNode = {
          id: nodeId,
          name: nodeName,
          level: level,
          category: level === 0 ? categoryIndex : Math.floor((categoryIndex - 1) / 2),
          symbolSize: nodeSize,
          value: nodeName,
          itemStyle: {
            color: colors[level === 0 ? categoryIndex : Math.floor((categoryIndex - 1) / 2) % colors.length]
          }
        };

        if (level === 0) {
          categories.push({
            name: nodeName,
            itemStyle: {
              color: colors[categoryIndex % colors.length]
            }
          });
          categoryIndex++;
        }
        
        nodes.push(currentNode);

        if (parentId !== null) {
          links.push({
            source: parentId,
            target: nodeId,
            lineStyle: {
              color: colors[Math.floor((categoryIndex - 1) / 2) % colors.length],
              width: Math.max(3 - level, 1)
            }
          });
        }

        if (node.children) {
          node.children.forEach(child => traverse(child, nodeId, level + 1));
        }
      };

      traverse(treeData);

      return {
        nodes,
        links,
        categories
      };
    },
    initChart() {
      const chartDom = this.$refs.chart;
      if (!chartDom) return;

      this.chart = echarts.init(chartDom);
      
      // 添加点击事件监听
      this.chart.on('click', (params) => {
        this.handleNodeClick(params);
      });

      const graphData = this.processedData;
      
      const option = {
        // legend: {
        //   data: graphData.categories.map(category => category.name),
        //   orient: 'vertical',
        //   right: 10,
        //   top: 'center'
        // },
        backgroundColor: '#f5f6fb',
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          type: 'graph',
          layout: 'force',
          data: graphData.nodes,
          links: graphData.links,
          categories: graphData.categories,
          roam: true,
          draggable: true,
          symbol: 'circle',
          zoom: 0.6,
          label: {
            show: true,
            position: 'right',
            formatter: '{b}',
            fontSize: 12,
            color: '#333'
          },
          labelLayout: {
            hideOverlap: true
          },
          scaleLimit: {
            min: 0.4,
            max: 2
          },
          lineStyle: {
            curveness: 0.3
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 4
            }
          },
          force: {
            repulsion: 300,
            gravity: 0.1,
            edgeLength: [50, 150],
            layoutAnimation: true,
            friction: 0.8
          }
        }]
      };

      this.chart.setOption(option);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    async handleNodeClick(params) {
      // console.log('进入 handleNodeClick，判断条件：', {
      //   hasData: !!params.data,
      //   level: params.data?.level,
      //   isLevelGE2: params.data?.level >= 0
      // });
      
      if (params.data && params.data.level >= 0) {
        try {
          this.drawerVisible = true;
          this.loading = true;
          this.isExpanded = false;
          
          const response = await knowledgeGraph.getKnowledgeGraphDetail(params.data.id);
          this.nodeDetail = response.data;
          
          this.$nextTick(() => {
            if (!this.drawerVisible) {
              this.drawerVisible = true;
            }
          });
        } catch (error) {
          console.error('获取知识图谱节点详情失败：', error);
          this.$message.error('获取节点详情失败');
        } finally {
          this.loading = false;
        }
      } else {
      }
    },

    handleExpand() {
      this.isExpanded = true;
    },

    handleCollapse() {
      this.isExpanded = false;
    },

    handleClose() {
      this.drawerVisible = false;
      this.isExpanded = false;
    },

    handleOutsideClick(event) {
      if (this.drawerVisible) {
        const panel = document.querySelector('.detail-panel');
        const chart = document.querySelector('.chart');
        if (panel && !panel.contains(event.target) && (!chart || !chart.contains(event.target))) {
          this.handleClose();
        }
      }
    },

    handleChartClick(event) {
      event.stopPropagation();
    }
  },
  computed: {
    hasNoDetailData() {
      const detail = this.nodeDetail;
      // 检查除了 nodeName 之外的其他字段是否都为空
      return !detail.nodeAlias && 
             !detail.nodeAttributes && 
             !detail.nodeDescription && 
             !detail.nodePhysicalSignificance && 
             !detail.nodeChemicalSignificance && 
             !detail.nodeMathematicalDependency && 
             !detail.nodeExperimentalBasis && 
             !detail.nodeHistoricalBackground && 
             !detail.nodeTypicalCases && 
             !detail.nodeFrontier;
    }
  }
};
</script>

<style lang="scss" scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 100px);
  min-height: 600px;
  overflow: visible;
  background: #f5f6fb;
}

.chart {
  width: 100%;
  height: 100%;
}

.detail-panel {
  position: absolute;
  right: -420px;
  width: 400px;
  height: 785px;
  z-index: 9999;
  top: 10px;
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(13px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  box-shadow: rgba(142, 142, 142, 0.19) 0px 6px 15px 0px;
  border-radius: 15px;
  color: rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  opacity: 0;
  pointer-events: none;
  
  &.show {
    right: 10px;
    opacity: 1;
    pointer-events: auto;
  }
  
  &.expanded {
    width: 800px;
  }

  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .header-left {
      .expand-btn {
        cursor: pointer;
        color: #333;
        font-size: 14px;
        
        &:hover {
          color: #40a9ff;
        }
      }
    }

    .header-right {
      .close-btn {
        cursor: pointer;
        color: #333;
        font-size: 20px;
        line-height: 1;
        padding: 4px 8px;
        
        &:hover {
          color: #666;
        }
      }
    }
  }

  .node-info {
    padding: 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .attr-tag {
      display: inline-block;
      padding: 1px 6px;
      border-radius: 5px;
      font-size: 14px;
      margin-bottom: 8px;
    }

    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
      font-weight: bold;
    }
  }

  .detail-content {
    flex: 1;
    padding: 16px;
    position: relative;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .attr-tag {
      display: inline-block;
      padding: 1px 6px;

      border-radius: 5px;
      font-size: 14px;
      margin-bottom: 8px;
    }

    p {
      margin: 0;
      padding: 16px;
      background: rgba(225, 226, 227, 0.8);
      border-radius: 8px;
      color: #333;
      line-height: 1.8;
      font-size: 14px;
    }
  }
}

.detail-body {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: transparent;
  position: relative;
}

.no-data-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  align-items: center;
  z-index: 1;

  .no-data-text {
    font-size: 16px;
    color: #666;
    padding: 5px 30px;
    background-color: #f5f5f5;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}
.no-data-img{
  width: 250px;
  height: 250px;
}
.attr-tag1{
      background: #b0a4e3;
      color: #f0f0f4;

}
.attr-tag2{
      background: #ffb61e;
      color: #f0f0f4;
}
.attr-tag3{
  background: #def3ec;
  color: #00ca8e;
}
.attr-tag4{
  background: #eacd76;
  color: #f0f0f4;
}
.attr-tag5{
  background: #00e09e;
  color: #f0f0f4;
}
.attr-tag6{
  background: #68be8d;
  color: #f0f0f4;
}
.attr-tag7{
  background: #89c3eb;
  color: #f0f0f4;
}
.attr-tag8{
  background: #cc7eb1;
  color: #f0f0f4;
}
.attr-tag9{
  background: #a6a5c4;
  color: #f0f0f4;
}
.attr-tag10{
  background: #59b9c6;
  color: #f0f0f4;
}
.attr-tag11{
  background: #88cb7f;
  color: #f0f0f4;
}
</style>